<?php
namespace app\common\model;

use app\common\model\Common as CommonModel;
use think\facade\Db;

use app\common\model\Users as UsersModel;
use app\common\model\Wechat as WechatModel;

class JSSDK extends CommonModel
{

    protected $name = 'wechat';

    private $appId = 'wxe5d55d481983958e';
    private $appSecret = 'def0acf61910502d9e3f0104c0eee4bf';


    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        //$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url = "https://www.pzcgj.cn/index/loaned/loaned_form.html";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode($this->get_php_file("jsapi_ticket.php"));

        $wechat = Db::name('wechat')->where('id','=',3)->find();

        if ( !$wechat || $wechat['expires_in'] < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = curlGet($url);
            $arr = json_decode($res,true);
            $ticket = $arr['ticket'];
            if ($ticket) {
                $data['name'] = 'jssdk_JsApi_ticket';
                $data['access_token'] = $ticket;
                $data['expires_in'] = 7000 + time();
                $data['add_date'] = date('Y-m-d',time());
                Db::name('wechat')->where('id','=',3)->update($data);
            }
        } else {
            $ticket = $wechat['access_token'];
        }

        return $ticket;
    }

    public function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode($this->get_php_file("access_token.php"));
        $wechat = Db::name('wechat')->where('id','=',2)->find();

        if ( !$wechat || $wechat['expires_in'] < time()) {
            // 如果是企业号用以下URL获取access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
            $res = curlGet($url);
            $arr = json_decode($res,true);
            $access_token = $arr['access_token'];
            if ($access_token) {
                $data['name'] = 'jssdk_access_token';
                $data['access_token'] = $arr['access_token'];
                $data['expires_in'] = 7000 + time();
                $data['add_date'] = date('Y-m-d',time());
                Db::name('wechat')->where('id','=',2)->update($data);
            }
        } else {
            $access_token = $wechat['access_token'];
        }
        return $access_token;
    }


}